package com.example.pucha_xian.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.example.pucha_xian.Class.CPoint;
import com.example.pucha_xian.R;
import com.example.pucha_xian.common.Ablum;
import com.example.pucha_xian.common.ColView;
import com.example.pucha_xian.common.Convert;
import com.example.pucha_xian.common.DataInput;
import com.example.pucha_xian.common.FileUtil;
import com.example.pucha_xian.common.PhotoConfig;
import com.example.pucha_xian.common.SpinnerConfig;
import com.example.pucha_xian.common.UserUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import cn.hzw.doodle.DoodleActivity;
import cn.hzw.doodle.imagepicker.ImageLoader;

public class PhotoFormActivity extends Activity {
    private TimePickerView pvTime;
    private String id, name, grade, bzlb, qjzp, pmzp, bzzp,remark;
    private Context context;
    private ImageView iv_qjzp, iv_pmzp, iv_bzzp;
    private Button bt_edit, bt_register;
    private EditText et_id, et_name, et_grade, et_remark;
    private Spinner sp_bzlb;
    private ViewGroup contentView;
    private CPoint cPoint;
    private Boolean FLAG1, FLAG2, FLAG3;
    private double uploadlat;
    private double uploadlng;
    private String token;
    private String ID;
    private Uri imageUri;
    public static File tempFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form_photo);
        SharedPreferences sharedPreferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", null);
        Bundle bundle = getIntent().getExtras();
        uploadlat=bundle.getDouble("lat");
        uploadlng=bundle.getDouble("lng");
        initForm();
        intiLister();
    }

    //初始化界面，控件绑定，日期初始化
    private void initForm() {
        context = PhotoFormActivity.this;

        contentView = findViewById(R.id.photo_grid);
//        ColView.setDisAble(contentView);//禁止编辑
        et_id = findViewById(R.id.photo_id);
        et_name = findViewById(R.id.photo_name);
        et_grade = findViewById(R.id.photo_grade);
        sp_bzlb = findViewById(R.id.photo_bzlb);
        et_remark = findViewById(R.id.photo_remark);
        iv_qjzp = findViewById(R.id.imageview_qjzp);
        iv_pmzp = findViewById(R.id.imageview_pmzp);
        iv_bzzp = findViewById(R.id.imageview_bzzp);
        bt_edit = findViewById(R.id.photo_edit);
        bt_register = findViewById(R.id.photo_register);
        Bundle bundle = getIntent().getExtras();
        SharedPreferences preferences = getSharedPreferences("PuCha", Context.MODE_PRIVATE);
        assert bundle != null;
        cPoint = (CPoint) bundle.getSerializable("point");
        ID = cPoint.getId();
        et_id.setText(cPoint.getPointID());
        et_name.setText(cPoint.getName());
        et_grade.setText(cPoint.getGrade());
        if (cPoint.getBzlb() != null) {
            sp_bzlb.setSelection(SpinnerConfig.bzlb(cPoint.getBzlb()));
        }
        et_remark.setText(cPoint.getRemark());
        if (cPoint.getUploadpanorama() != null && !cPoint.getUploadpanorama().equals("")) {
            Glide.with(context).load(UserUtil.address + cPoint.getUploadpanorama()).into(iv_qjzp);
//                iv_qjzp.setImageBitmap(PhotoConfig.showPhoto(cPoint.getPanorama()));
        }
        if (cPoint.getUploadbust() != null && !cPoint.getUploadbust().equals("")) {
            Glide.with(context).load(UserUtil.address + cPoint.getUploadbust()).into(iv_pmzp);
//                iv_pmzp.setImageBitmap(PhotoConfig.showPhoto(cPoint.getBust()));
        }
        if (cPoint.getUploadcloseup() != null && !cPoint.getUploadcloseup().equals("")) {
            Glide.with(context).load(UserUtil.address + cPoint.getUploadcloseup()).into(iv_bzzp);
//                iv_bzzp.setImageBitmap(PhotoConfig.showPhoto(cPoint.getCloseup()));
        }
    }


    //控件监听事件
    private void intiLister() {
        FLAG1 = false;
        FLAG2 = false;
        FLAG3 = false;

        //三个照片放置框的监听事件,长按替换照片
        iv_qjzp.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (qjzp != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + qjzp);
                    if (file.exists()) {
                        file.delete();
                    }
                }
                Toast.makeText(context, "开始拍照", Toast.LENGTH_SHORT).show();
                openCamera(PhotoFormActivity.this, PhotoConfig.REQUEST_QJZP);
                return true;
            }
        });
        iv_pmzp.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (pmzp != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + pmzp);
                    if (file.exists()) {
                        file.delete();
                    }
                }
                Toast.makeText(context, "开始拍照", Toast.LENGTH_SHORT).show();
                openCamera(PhotoFormActivity.this, PhotoConfig.REQUEST_PMZP);
                return true;
            }
        });
        iv_bzzp.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (bzzp != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + bzzp);
                    if (file.exists()) {
                        file.delete();
                    }
                }
                Toast.makeText(context, "开始拍照", Toast.LENGTH_SHORT).show();
                openCamera(PhotoFormActivity.this, PhotoConfig.REQUEST_BZZP);
                return true;
            }
        });

        //点击进入照片编辑界面
        //点击进入照片放大
        iv_qjzp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FLAG1) {
                    Ablum.imageMax(qjzp, context, true);
                } else {
                    if (cPoint.getUploadpanorama() != null && !cPoint.getUploadpanorama().equals("")) {
                        Ablum.imageMax(UserUtil.address + cPoint.getUploadpanorama(), context, false);
                    }
                }
//                Ablum.Doodle(PhotoFormActivity.this, qjzp, PhotoConfig.REQ_QJZP);
            }
        });
        iv_pmzp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FLAG2) {
                    Ablum.imageMax(pmzp, context, true);
                } else {
                    if (cPoint.getUploadbust() != null && !cPoint.getUploadbust().equals("")) {
                        Ablum.imageMax(UserUtil.address + cPoint.getUploadbust(), context, false);
                    }
                }
//                Ablum.Doodle(PhotoFormActivity.this, pmzp, PhotoConfig.REQ_PMZP);
            }
        });
        iv_bzzp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FLAG3) {
                    Ablum.imageMax(bzzp, context, true);
                } else {
                    if (cPoint.getUploadcloseup() != null && !cPoint.getUploadcloseup().equals("")) {
                        Ablum.imageMax(UserUtil.address + cPoint.getUploadcloseup(), context, false);
                    }
                }
//                Ablum.Doodle(PhotoFormActivity.this, bzzp, PhotoConfig.REQ_BZZP);
            }
        });

        //提交，获取界面所有输入值
        bt_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                id = et_id.getText().toString().trim();
                name = et_name.getText().toString().trim();
                grade = et_grade.getText().toString().trim();
                bzlb = sp_bzlb.getSelectedItem().toString();
                remark = et_remark.getText().toString().trim();
                if (qjzp == null && cPoint.getUploadpanorama() != null) {
                    qjzp = cPoint.getUploadpanorama();
                } else if (qjzp != null && cPoint.getUploadpanorama() != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + cPoint.getUploadpanorama());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                if (pmzp == null && cPoint.getUploadbust() != null) {
                    pmzp = cPoint.getUploadbust();
                } else if (pmzp != null && cPoint.getUploadbust() != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + cPoint.getUploadbust());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                if (bzzp == null && cPoint.getUploadcloseup() != null) {
                    bzzp = cPoint.getUploadcloseup();
                } else if (bzzp != null && cPoint.getUploadcloseup() != null) {
                    File file = new File(PhotoConfig.sdCard + PhotoConfig.PHOTO_PATH + cPoint.getUploadcloseup());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                /*if (!id.isEmpty() &&!name.isEmpty() && !pcz.isEmpty() && !day.isEmpty() &&
                        !qjzp.isEmpty() && !pmzp.isEmpty() && !bzzp.isEmpty()) {*/
                CPoint curPoint = new CPoint(ID, id, name, grade, bzlb, uploadlat, uploadlng, qjzp, pmzp, bzzp, remark);
                try {
                    Map<String, String> map = Convert.object2Map(curPoint);
                    DataInput.update(map, context, token);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(PhotoFormActivity.this, ArcgisActivity.class);
                            startActivity(intent);
                        }
                    }, 3000);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
               /* } else {
                    Toast.makeText(context, "保存失败：请输入完整的信息", Toast.LENGTH_SHORT).show();
                }*/
            }
        });

        //获取控件的编辑
        bt_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ColView.setAble(contentView);
                Toast.makeText(context, "可以开始编辑了", Toast.LENGTH_SHORT).show();
            }
        });

    }

    //相册选择的返回结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        id = et_id.getText().toString().trim();
        name = et_name.getText().toString().trim();
        assert data != null;
        switch (requestCode) {
            case PhotoConfig.REQUEST_QJZP:
                qjzp = Selectimage(data, resultCode, iv_qjzp, name);
                FLAG1 = true;
                break;
            case PhotoConfig.REQUEST_PMZP:
                pmzp = Selectimage(data, resultCode, iv_pmzp, name);
                FLAG2 = true;
                break;
            case PhotoConfig.REQUEST_BZZP:
                bzzp = Selectimage(data, resultCode, iv_bzzp, name);
                FLAG3 = true;
                break;
            case PhotoConfig.REQ_QJZP:
                Dooleedit(data, resultCode, iv_qjzp, context);
                break;
            case PhotoConfig.REQ_PMZP:
                Dooleedit(data, resultCode, iv_pmzp, context);
                break;
            case PhotoConfig.REQ_BZZP:
                Dooleedit(data, resultCode, iv_bzzp, context);
                break;
            default:
                break;
        }
    }

    //相册选择及拍照留存
    public String Selectimage(Intent data, int resultCode, ImageView view, String name) {

        if (resultCode == RESULT_OK) {
            Bitmap bitmap = FileUtil.AddTimeWatermark(FileUtil.amendRotatePhoto(tempFile.getAbsolutePath()));//添加时间水印
            view.setImageBitmap(bitmap);
            return FileUtil.savePhoto(bitmap, name);
        }
        return null;
    }

    //照片的编辑、涂鸦
    public void Dooleedit(Intent data, int resultCode, ImageView view, Context context) {
        if (data == null) {
            return;
        }
        if (resultCode == DoodleActivity.RESULT_OK) {
            String path = data.getStringExtra(DoodleActivity.KEY_IMAGE_PATH);
            Log.e("path", "" + path);
            if (TextUtils.isEmpty(path)) {
                return;
            }
            ImageLoader.getInstance(context).display(view, path);
        } else if (resultCode == DoodleActivity.RESULT_ERROR) {
            Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
        }
    }

    public void openCamera(Activity activity, int request) {
        //獲取系統版本
        int currentapiVersion = android.os.Build.VERSION.SDK_INT;
        // 激活相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            @SuppressLint("SimpleDateFormat")
            SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                    "yyyy_MM_dd_HH_mm_ss");
            String filename = timeStampFormat.format(new Date());
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    filename + ".jpg");
            if (currentapiVersion < 24) {
                // 从文件中创建uri
                imageUri = Uri.fromFile(tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            } else {
                //兼容android7.0 使用共享文件的形式
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, tempFile.getAbsolutePath());
                //检查是否有存储权限，以免崩溃
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请WRITE_EXTERNAL_STORAGE权限
                    Toast.makeText(this,"请开启存储权限",Toast.LENGTH_SHORT).show();
                    return;
                }
                imageUri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
        }
        // 开启一个带有返回值的Activity，请求码为request
        activity.startActivityForResult(intent, request);
    }

    /*
     * 判断sdcard是否被挂载
     */
    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /*
     *  获取多媒体图片真实路径
     */
//    private String getRealPathFromURI(Uri contentURI) {
//        String result;
//        Cursor cursor = null;
//        try {
//            cursor = getContentResolver().query(contentURI, null, null, null, null);
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
//        if (cursor == null) {
//            result = contentURI.getPath();
//        } else {
//            cursor.moveToFirst();
//            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
//            result = cursor.getString(idx);
//            cursor.close();
//        }
//        return result;
//    }
}
